package com.quyunshuo.module.home.music

import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.media.MediaPlayer
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import java.io.IOException
object MusicPlayer {

    private var mediaPlayer: MediaPlayer? = null
    private var currentMusic: Music? = null
    private var isPlaying = false
    private var currentPosition = 0 // 只存储当前歌曲的播放进度
    private var handler = Handler(Looper.getMainLooper())
    private var progressCallback: ((Int, Int) -> Unit)? = null
    private var stateCallback: ((Boolean) -> Unit)? = null
    private var currentMusicCallback:((Music)->Unit)?=null//当前播放的音乐，只要用于自动切换歌曲的时候使用，告知界面的变化
    private var musicList:List<Music>? =null
    // 当前播放索引
    private var currentIndex: Int = -1


    private val updateProgress = object : Runnable {
        override fun run() {
            if (isPlaying && mediaPlayer != null) {
                currentPosition = mediaPlayer!!.currentPosition
                val total = mediaPlayer!!.duration
                progressCallback?.invoke(currentPosition, total)
                handler.postDelayed(this, 1000)
            }
        }
    }
    // 播放下一首
    fun playNext(context: Context) {
        if (musicList == null || musicList!!.isEmpty()) return

        val nextIndex = (currentIndex + 1) % musicList!!.size
        playAtIndex(context, nextIndex)
    }

    // 播放上一首
    fun playPrevious(context: Context) {
        if (musicList == null || musicList!!.isEmpty()) return

        val prevIndex = if (currentIndex <= 0) {
            musicList!!.size - 1 // 循环到最后一首
        } else {
            currentIndex - 1
        }
        playAtIndex(context, prevIndex)
    }

    // 播放指定索引的歌曲
    private fun playAtIndex(context: Context, index: Int) {
        if (index < 0 || index >= musicList!!.size) return

        val music = musicList!![index]
        currentMusicCallback?.invoke(music)
        init(context, music, index)
    }

    fun init(context: Context, music: Music, index: Int) {
        // 更新当前索引
        currentIndex = index
        // 如果点击的是同一首歌曲
        if (currentMusic?.id == music.id) {
            if (isPlaying) {
                pause()
            } else {
                // 从当前进度位置继续播放
                playFromPosition(currentPosition)
            }
            return
        }

        // 处理新歌曲 - 重置进度
        currentPosition = 0
        currentMusic = music

        try {
            mediaPlayer?.release()
            mediaPlayer = MediaPlayer().apply {
                setDataSource(context, Uri.parse(music.path))
                prepareAsync()
                setOnPreparedListener {
                    // 新歌曲总是从0开始播放
                    seekTo(0)
                    play()
                }
                setOnCompletionListener {
                    MusicPlayer.isPlaying = false
                    stateCallback?.invoke(false)
                    handler.removeCallbacks(updateProgress)
                    // 播放完成时重置进度
                    MusicPlayer.currentPosition = 0
                    // 新增：播放完成后自动下一首
                    playNext(context)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun play() {
        mediaPlayer?.start()
        isPlaying = true
        stateCallback?.invoke(true)
        handler.post(updateProgress)
    }

    fun playFromPosition(position: Int) {
        mediaPlayer?.seekTo(position)
        play()
    }

    fun pause() {
        mediaPlayer?.let {
            // 暂停时更新当前进度
            currentPosition = it.currentPosition
            it.pause()
        }
        isPlaying = false
        stateCallback?.invoke(false)
        handler.removeCallbacks(updateProgress)
    }

    fun stop() {
        mediaPlayer?.let {
            // 停止时更新当前进度
            currentPosition = it.currentPosition
            it.stop()
            it.release()
        }
        mediaPlayer = null
        isPlaying = false
        stateCallback?.invoke(false)
        handler.removeCallbacks(updateProgress)
    }

    fun seekTo(position: Int) {
        mediaPlayer?.seekTo(position)
        currentPosition = position
    }

    fun isPlaying(): Boolean = isPlaying

    fun getCurrentMusic(): Music? = currentMusic

    fun getCurrentIndex():Int = currentIndex

    fun getCurrentPosition(): Int = currentPosition

    fun getDuration(): Int = mediaPlayer?.duration ?: 0

    fun getMusicList():List<Music>? = musicList

    fun setProgressCallback(callback: (Int, Int) -> Unit) {
        progressCallback = callback
    }

    fun setStateCallback(callback: (Boolean) -> Unit) {
        stateCallback = callback
    }

    fun setCurrentMusicCallback(callback: (Music) -> Unit) {
        currentMusicCallback = callback
    }

    fun release() {
        stop()
        // 重置进度
        currentPosition = 0
        progressCallback = null
        stateCallback = null
    }

    fun loadMusic(context: Context): List<Music> {
        val musicList = mutableListOf<Music>()
        val resolver: ContentResolver = context.contentResolver

        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM_ID
        )

        val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0"

        val sortOrder = "${MediaStore.Audio.Media.TITLE} ASC"

        val cursor: Cursor? = resolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            sortOrder
        )

        cursor?.use {
            val idColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val titleColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
            val artistColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)
            val albumColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)
            val durationColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
            val dataColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
            val albumIdColumn = it.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)

            while (it.moveToNext()) {
                val id = it.getLong(idColumn)
                val title = it.getString(titleColumn)
                val artist = it.getString(artistColumn)
                val album = it.getString(albumColumn)
                val duration = it.getLong(durationColumn)
                val path = it.getString(dataColumn)
                val albumId = it.getLong(albumIdColumn)

                musicList.add(Music(id, title, artist, album, duration, path, albumId))
            }
        }

        this.musicList = musicList
        return musicList
    }

    // 格式化时长 (毫秒 -> mm:ss)
    fun formatDuration(duration: Long): String {
        val minutes = (duration / 1000) / 60
        val seconds = (duration / 1000) % 60
        return String.format("%02d:%02d", minutes, seconds)
    }
}